package com.acheng.ws.client.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import com.acheng.ws.client.listener.*;

import java.util.concurrent.CountDownLatch;

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private final WebSocketClientHandshaker handshaker;
    private final WebSocketListener listener;
    private ChannelPromise handshakeFuture;
    private Channel channel;
    private CountDownLatch mCountDownLatch;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker, WebSocketListener listener) {
        this.handshaker = handshaker;
        this.listener = listener;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        channel = ctx.channel();
        handshakeFuture = ctx.newPromise();
        handshakeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
            }
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        channel = ctx.channel();
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        channel = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            try {
                handshaker.finishHandshake(channel, (FullHttpResponse) msg);
                handshakeFuture.setSuccess();
                listener.onOpen(channel, (FullHttpResponse) msg);
            } catch (WebSocketHandshakeException e) {
                handshakeFuture.setFailure(e);
                listener.onFailure(channel, e, (FullHttpResponse) msg);
            }
            return;
        }

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;

            listener.onFailure(channel, new IllegalStateException(
                    "Unexpected FullHttpResponse (getStatus=" + response.status() +
                            ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'), (FullHttpResponse) msg);
            return;
        }

        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            this.listener.onMessage(channel, ((TextWebSocketFrame) frame).text());
        } else if (frame instanceof BinaryWebSocketFrame) {
            this.listener.onMessage(channel, frame.content().array());
        } else if (frame instanceof PongWebSocketFrame) {
            //这里需要计时
            mCountDownLatch.countDown();
        } else if (frame instanceof CloseWebSocketFrame) {
            this.listener.onClosed(channel, ((CloseWebSocketFrame) frame).statusCode(), ((CloseWebSocketFrame) frame).reasonText());
            ctx.close();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
        listener.onFailure(ctx.channel(), cause);
    }

    public synchronized long ping() {
        mCountDownLatch = new CountDownLatch(1);
        long timeMillis = System.currentTimeMillis();
        //发送ping消息，接收到后，返回延迟时间
        try {
            if (!this.channel.isActive()) {
                throw new RuntimeException("链接失败！请重新连接！");
            }
            this.channel.writeAndFlush(new PingWebSocketFrame());
            mCountDownLatch.await();
            return (System.currentTimeMillis() - timeMillis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 9999;
    }

    public boolean isConnection() {
        return this.channel.isActive();
    }

    public void send(String text) {
        if (!this.channel.isActive()) {
            throw new RuntimeException("链接失败！请重新连接！");
        }
        this.channel.writeAndFlush(new TextWebSocketFrame(text));
    }

    public void send(byte[] bytes) {
        if (!this.channel.isActive()) {
            throw new RuntimeException("链接失败！请重新连接！");
        }
        ByteBuf buffer = this.channel.alloc().buffer(bytes.length);
        this.channel.writeAndFlush(new BinaryWebSocketFrame(buffer.writeBytes(bytes)));
    }

}
